import React, { Component } from 'react';
import { connect } from 'react-redux';
import HomeLove from './HomeLove.jsx';
import { handlerSliderToBottom } from '../../../util/dom';
import { fetchHomeLove } from '../../../api/home';
import Loading from '../../../components/Loading';

const START_PAGE = 1;

class LoveWrapper extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: null,
      page: START_PAGE,
      isFetching: true,
      hasMore: true
    }
  }

  componentDidMount() {
    // todo 这里需要在跳转路由时清除window上的onscroll事件监听?
    handlerSliderToBottom(30, this.handleLoadMore.bind(this));
    fetchHomeLove(START_PAGE, this.props.city.name).then(data => {
      this.setState({data: data.list, isFetching: false, hasMore: data.total > START_PAGE})
    })
  }

  handleLoadMore = () => {
    const {page, hasMore, isFetching} = this.state;
    const {city} = this.props;
    const nextPage = page + 1;
    if(!hasMore || isFetching) {
      return;
    }
    this.setState({isFetching: true}, () => {
      fetchHomeLove(nextPage, city.name).then(data => {
        this.setState(prevState => ({
          data: prevState.data.concat(data.list),
          page: nextPage,
          isFetching: false,
          hasMore: data.total > nextPage
        }))
      })
    })
  }

  render() {
    const {isFetching, hasMore, data} = this.state;
    if(!data) {
      return <Loading/>;
    }
    return (
      <HomeLove data={data} onLoadMore={this.handleLoadMore} isLoading={isFetching} hasMore={hasMore}/>
    )
  }
}

export default connect(state => ({
  city: state.home.city
}))(LoveWrapper);